#!/bin/bash

################################################################################
function md5str()
{
    echo "Calculate simple string: [$1]"; echo -n "MD5: "; echo -n "$1" | md5sum;
}
export -f md5str

# make
################################################################################
function make()
{
	local start_time=$(date +"%s")
	$(echo command make) "$@"
	local ret=$?
	local end_time=$(date +"%s")

	local tdiff=$(($end_time - $start_time))
	local hours=$(($tdiff / 3600 ))
	local mins=$((($tdiff % 3600) / 60))
	local secs=$(($tdiff % 60))

	echo
	if [ $ret -eq 0 ] ; then
		echo -n -e "\033[1;32m #### make $@ completed successfully!"
	else
		echo -n -e "\033[1;31m #### make target $@ failed !!!"
	fi
	if [ $hours -gt 0 ] ; then
		printf "(%02g:%02g:%02g (hh:mm:ss))" $hours $mins $secs
	elif [ $mins -gt 0 ] ; then
		printf "(%02g:%02g (mm:ss))" $mins $secs
	elif [ $secs -gt 0 ] ; then
		printf "(%s seconds)" $secs
	fi
	echo -e " ####\033[1;0m"
	echo
	return $ret
}
#export -f make

function make-target()
{
	make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ {split($1,A,/ /); for(i in A)print A[i]}' | sort -u
}
export -f make-target

# 解压
################################################################################
function x() {
    if [ -f $1 ] ; then
        case $1 in
            *.tar.bz2)   tar xjf $1     ;;
            *.tar.gz)    tar xzf $1     ;;
            *.bz2)       bunzip2 $1     ;;
            *.rar)       unrar e $1     ;;
            *.gz)        gunzip $1      ;;
            *.tar)       tar xf $1      ;;
            *.tbz2)      tar xjf $1     ;;
            *.tgz)       tar xzf $1     ;;
            *.zip)       unzip $1       ;;
            *.Z)         uncompress $1  ;;
            *.7z)        7z x $1        ;;
            *)     echo "'$1' cannot be extracted via extract()" ;;
        esac
    else
        echo "'$1' is not a valid file"
    fi
}

function 7z-comp()
{
	local comp_package_name=$1
	local comp_dir=$2
	local suff="bin"

	type 7z > /dev/null 2>&1
	if [ $? -ne 0 ]; then
		echo -e "\nsudo apt install p7zip-full\n"
		return -1
	fi
	if [ "${comp_package_name##*.}"x != "${suff}"x ] ;then
		echo "the compressed package suffix is incorrect. suffix [${suff}]"
		return -1
	fi
	if [ ! -d $comp_dir ]; then
		echo "the compressed directory does not exist."
		return -1
	fi

	local G7ZP=$(echo -n "g7zp123" | sha512sum | awk '{print $1}')
	cmd="7z a -t7z -m0=lzma2 -mx=9 -mfb=64 -md=32m -ms=on -mhe=on -p'${G7ZP}' $comp_package_name $comp_dir"
	echo "$cmd"
	$cmd
	if [ $? -ne 0 ]; then
		echo "Compression error."
		return 1
	fi

	# fix head: 7F 45 4C 46 01 01 (elf)
	fix_header=(0x7f 0x45 0x4c 0x46 0x01 0x01)
	for i in "${!fix_header[@]}"
	do
		echo "$i:${fix_header[$i]}" | xxd -r - $comp_package_name
	done
}
export -f 7z-comp

function 7z-decomp()
{
	local decomp_package_name=$1
	local decomp_org_package_name="${decomp_package_name}.org"
	local suff="bin"

	type 7z > /dev/null 2>&1
	if [ $? -ne 0 ]; then
		echo -e "\nsudo apt install p7zip-full\n"
		return -1
	fi
	if [ "${decomp_package_name##*.}"x != "${suff}"x ] ;then
		echo "the decompressed package suffix is incorrect. suffix [${suff}]"
		return -1
	fi

	cp $decomp_package_name $decomp_org_package_name -arp

	# hexdump: 7a37 afbc 1c27 0400 (37 7A BC AF 27 1C)
	fix_header=(0x37 0x7a 0xbc 0xaf 0x27 0x1c)
	for i in "${!fix_header[@]}"
	do
		echo "$i:${fix_header[$i]}" | xxd -r - $decomp_org_package_name
	done

	local G7ZP=$(echo -n "g7zp123" | sha512sum | awk '{print $1}')
	cmd="7z x -p'${G7ZP}' $decomp_org_package_name"
	echo "$cmd"
	$cmd
}
export -f 7z-decomp

# 代理
################################################################################
# 命令行配置：系统设置 -> 网络 -> 网络代理
# gsettings get org.gnome.system.proxy mode  #获取当前模式
# set, 'none' \ 'manual' \ 'auto'
function proxy_on() {
	#sudo /opt/clash/auto_update.sh
	sudo systemctl restart clash.service

	gsettings set org.gnome.system.proxy.http host '127.0.0.1'
	gsettings set org.gnome.system.proxy.http port 7890
	gsettings set org.gnome.system.proxy.https host '127.0.0.1'
	gsettings set org.gnome.system.proxy.https port 7890
	gsettings set org.gnome.system.proxy.ftp host ''
	gsettings set org.gnome.system.proxy.ftp port 0
	gsettings set org.gnome.system.proxy.socks host '127.0.0.1'
	gsettings set org.gnome.system.proxy.socks port 7890

	gsettings set org.gnome.system.proxy mode 'manual';

	sudo systemctl status clash.service --no-pager
	echo "*****************************************"
	echo "*  Manage URL: http://clash.razord.top  *"
	echo "*****************************************"
}
function proxy_off() {
	gsettings set org.gnome.system.proxy.http host ''
	gsettings set org.gnome.system.proxy.http port 0
	gsettings set org.gnome.system.proxy.https host ''
	gsettings set org.gnome.system.proxy.https port 0
	gsettings set org.gnome.system.proxy.ftp host ''
	gsettings set org.gnome.system.proxy.ftp port 0
	gsettings set org.gnome.system.proxy.socks host ''
	gsettings set org.gnome.system.proxy.socks port 0

	gsettings set org.gnome.system.proxy mode 'auto';

	sudo systemctl stop clash.service
	sudo systemctl status clash.service --no-pager
	# 删除proxy相关环境变量
	unset https_proxy http_proxy all_proxy no_proxy
}


# edge设置中文
function microsoft-edge-zh() {
	grep "LANGUAGE=ZH-CN.UTF-8" /opt/microsoft/msedge/microsoft-edge || sudo sed -i 'N;6a\export LANGUAGE=ZH-CN.UTF-8' /opt/microsoft/msedge/microsoft-edge
}

function gen_compile_commands() {
	if [ -f "CMakeLists.txt" ]; then
		echo -n "cmake generate compile_commands.json."
		local build_dir=`mktemp -d`
		cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=1 . -B $build_dir
		cp $build_dir/compile_commands.json .
		echo "Done."
	elif [ -f "scripts/clang-tools/gen_compile_commands.py" ] || [ -f "scripts/gen_compile_commands.py" ]; then
		echo -n "Linux kernel generate compile_commands.json."
		if [ -f "./scripts/gen_compile_commands.py" ]; then
			# kernel 5.4
			./scripts/gen_compile_commands.py
		else
			./scripts/clang-tools/gen_compile_commands.py
		fi
		if [ -f ".clangd" ] && [ ! -f ".clangd.bak" ]; then
			cp .clangd .clangd.bak
		fi
		cp ~/.vim/other/linux_kernel_clangd.cfg .clangd
		echo "Done."
	else
		echo "Not support."
		echo "  bear -- make -j8"
	fi
}

function hexdump-32bit() {
	local file=$1
	local len=$2
	if [ $# -lt 1 ]; then echo "Usage: $o <file> <len>"; return; fi

	len=${len:-256}
	hexdump -e '"%.2_ax: " 1/4 "%08x ""\n"' -n $len -v $file
}
